import { curveShow, visibility } from './csvUtils.js'
import { ref } from 'vue'
import Dygraph from 'dygraphs'
import colors from './colors.js'

let count = 0
export const path = '/3列数据.csv'
export const graph = null

export function initializeGraph(graphDiv) {
    graph = new Dygraph(graphDiv, path, {
        title: '2023.10.01数据展示',
        titleHeight: 50,
        xlabel: '时间',
        ylabel: '数值',
        axisLabelWidth: 50,
        drawPoints: true,
        colors,
        labelsDiv: document.getElementById('content'),
        legend: 'follow',
        strokeBorderWidth: 2,
        strokeBorderColor: ['blue', 'pink'],
        strokeWidth: 3.0,
        labelsUTC: true,
        gridLineWidth: 2,
        hideOverlayOnMouseOut: false,
        highlightCircleSize: 5,
        labelsSeparateLines: true,
        zoomCallback: function (minDate, maxDate) {
            const minZoomRange = 20 * 1000
            if (maxDate - minDate < minZoomRange) {
                graph.updateOptions({
                    dateWindow: [minDate, minDate + minZoomRange],
                    visibility,
                })
            }
        },
        axes: {
            x: {
                pixelsPerLabel: 100,
                axisLabelFormatter: function (d) {
                    const date = new Date(d)
                    const hours = String(
                        date.getHours() >= 8
                            ? date.getHours() - 8
                            : date.getHours() + 24 - 8
                    ).padStart(2, '0')
                    const minute = String(date.getMinutes()).padStart(2, '0')
                    const second = String(date.getSeconds()).padStart(2, '0')
                    return `${hours}:${minute}:${second}`
                },
            },
            y: {
                pixelsPerLabel: 30,
            },
        },
        plotter: [customPlotter],
        valueFormatter: showLabel,
    })
}

export function customPlotter(e) {
    console.log('111111')
    const g = e.dygraph
    const series = e.seriesIndex
    const ctx = e.drawingContext
    const points = e.allSeriesPoints[series] // 获取全部系列的数据点
    // 因为曲线绘制时，它内置循环会检测visibility属性，如果有false则直接不会进行循环，循环次数会少false的个数次，因此直接进行赋值会导致错位，使得曲线数据变化
    // 所以要检测当前是否为false，如果是false就跳过，直到找到true即需要绘制的曲线，这时候再将该索引下的数值赋值给曲线绘制的yval,这样就能解决错位的问题了
    for (let i = count; i < curveShow.value.length; i++) {
        if (curveShow.value[i].visible === true) {
            count = i
            break
        }
    }
    // 根据偏移修改y值
    if (curveShow.value) {
        // console.log('曲线绘制的第：', series, '数组的第：', count) // 检测是否错位
        // 防止用户在偏移的乘积上填入0或负数，如果填了就默认为乘数为0
        if (curveShow.value[count].offsetMultiplication <= 0) {
            curveShow.value[count].offsetMultiplication = 1
        }
        // 如果用户没有填写则默认加数为0
        if (!curveShow.value[count].offsetIncrement) {
            curveShow.value[count].offsetIncrement = 0
        }
        for (let i = 0; i < points.length; i++) {
            points[i].yval =
                points[i].yval *
                    Number(curveShow.value[count].offsetMultiplication) +
                Number(curveShow.value[count].offsetIncrement)
            // max = max > points[i].yval ? max : points[i].yval
            points[i].canvasy = g.toDomCoords(points[i].xval, points[i].yval)[1]
        }
    }

    ctx.beginPath()
    ctx.strokeStyle = e.color
    ctx.lineWidth = 1.2 // 控制线条粗细

    for (let i = 0; i < points.length - 1; i++) {
        if (i === 0) {
            ctx.moveTo(points[0].canvasx, points[0].canvasy)
            continue
        }
        const p1 = points[i]
        const p2 = points[i - 1]

        if (p1.xval - p2.xval > 1000) {
            // 如果x值的差大于 1000，则跳过绘制，检测是文件中是否有时间数据的缺失
            // 因为曲线的横坐标在csv中是以ISO 8601格式存储的，但Dygraphs会将其转化为纯数字的时间戳，一秒的差值就是1000
            ctx.moveTo(p1.canvasx, p1.canvasy)
            continue
        }

        if (isNaN(p2.yval)) {
            ctx.moveTo(p1.canvasx, p1.canvasy)
            continue
        }

        ctx.lineTo(p1.canvasx, p1.canvasy)
    }

    ctx.stroke()
    count++
    // 判断如果绘制到了最后一条线，则将计数器清0
    if (series === e.seriesCount - 1) {
        count = 0
    }
}

export function showLabel(yval, opts, seriesName, g, row, col) {
    if (col === 0) {
        const date = new Date(yval)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minute = String(date.getMinutes()).padStart(2, '0')
        const second = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minute}:${second}`
    }

    const Multiplication = Number(curveShow.value[col - 1].offsetMultiplication)
    const Increment = Number(curveShow.value[col - 1].offsetIncrement)
    const calculatedValue = (yval - Increment) / Multiplication
    return `${calculatedValue} * ${Multiplication} + ${Increment}`
}

export function button(graphDiv, graph, visibility) {
    console.log(graph)
    if (graph) {
        const currentZoom = graph.xAxisRange()
        graph.destroy()
        graph = null
        initializeGraph(graphDiv)
        if (currentZoom) {
            graph.updateOptions({
                dateWindow: currentZoom,
                visibility,
            })
        }
    }
}

export default { graph, path }
